const express = require('express');
const router = express.Router();
const { authenticateToken } = require('../middleware/auth');
const  PunchPlan  = require('../models/PunchPlan');
const  PunchRecord  = require('../models/PunchRecord');
// 创建打卡计划
router.post('/', authenticateToken, async (req, res) => {
  const { name, days, desc } = req.body;
  const userId = req.user.id; // 使用JWT中的userId

  try {
    // 检查用户已有的打卡计划数量
    const punchPlanCount = await PunchPlan.count({ where: { userId } });
    if (punchPlanCount >= 20) {
      return res.status(400).json({ message: '每个用户最多只能创建20个打卡计划' });
    }

    const punchPlan = await PunchPlan.create({ userId, name, days, desc });
    res.status(201).json(punchPlan);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// 获取用户的打卡计划
router.get('/', authenticateToken, async (req, res) => {
  const userId = req.user.id; // 使用JWT中的userId
  try {
    const punchPlans = await PunchPlan.findAll({ where: { userId } });

    // 生成当前日期的dayNo
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const dayNo = `${year}${month}${day}`;

    // 为每个打卡计划添加今天的打卡记录
    const punchPlansWithTodayRecord = await Promise.all(punchPlans.map(async (plan) => {
      const planData = plan.toJSON();

      // 查询今天的打卡记录
      const todayRecord = await PunchRecord.findOne({
        where: { punchPlanId: planData.id, dayNo }
      });

      // 添加今天的打卡记录到计划数据中
      planData.todayRecord = todayRecord || null;

      return planData;
    }));

    res.json(punchPlansWithTodayRecord);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// 检查用户在指定日期是否已打卡
router.get('/:id/check-punch/:dayNo', authenticateToken, async (req, res) => {
  const { id, dayNo } = req.params;
  const userId = req.user.id; // 使用JWT中的userId

  try {
    // 首先验证打卡计划是否属于用户
    const punchPlan = await PunchPlan.findOne({ where: { id, userId } });
    if (!punchPlan) {
      return res.status(404).json({ message: 'Punch plan not found or not owned by user' });
    }

    // 查询指定日期是否已有打卡记录
    const punchRecord = await PunchRecord.findOne({
      where: { punchPlanId: id, dayNo }
    });

    res.json({ punched: !!punchRecord });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// 根据ID获取打卡计划
router.get('/:id', authenticateToken, async (req, res) => {
  const { id } = req.params;
  const userId = req.user.id; // 使用JWT中的userId

  try {
    const punchPlan = await PunchPlan.findOne({ where: { id, userId } });
    if (!punchPlan) {
      return res.status(404).json({ message: 'Punch plan not found' });
    }
    res.json(punchPlan);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// 更新打卡计划
router.put('/:id', authenticateToken, async (req, res) => {
  const { id } = req.params;
  const { name, days, desc } = req.body;
  const userId = req.user.id; // 使用JWT中的userId

  try {
    const [updatedRowsCount] = await PunchPlan.update(
      { name, days, desc },
      { where: { id, userId } }
    );
    if (updatedRowsCount === 0) {
      return res.status(404).json({ message: 'Punch plan not found' });
    }
    const updatedPunchPlan = await PunchPlan.findOne({ where: { id, userId } });
    res.json(updatedPunchPlan);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// 删除打卡计划
router.delete('/:id', authenticateToken, async (req, res) => {
  const { id } = req.params;
  const userId = req.user.id; // 使用JWT中的userId

  try {
    const deletedRowsCount = await PunchPlan.destroy({ where: { id, userId } });
    if (deletedRowsCount === 0) {
      return res.status(404).json({ message: 'Punch plan not found or not owned by user' });
    }
    res.status(204).send();
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// 打卡记录功能
router.post('/:id/punch', authenticateToken, async (req, res) => {
  const { id } = req.params;
  const userId = req.user.id; // 使用JWT中的userId
  const { detail } = req.body;

  try {
    // 首先验证打卡计划是否属于用户
    const punchPlan = await PunchPlan.findOne({ where: { id, userId } });
    if (!punchPlan) {
      return res.status(404).json({ message: 'Punch plan not found or not owned by user' });
    }

    // 生成当前日期的dayNo
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const dayNo = `${year}${month}${day}`;

    // 检查是否已经打卡
    const existingRecord = await PunchRecord.findOne({
      where: { punchPlanId: id, dayNo }
    });

    if (existingRecord) {
      return res.status(400).json({ message: 'Already punched today' });
    }

    // 创建打卡记录
    const punchRecord = await PunchRecord.create({
      punchPlanId: id,
      dayNo,
      detail
    });

    // 增加已打卡次数
    await PunchPlan.increment('punched_count', {
      by: 1,
      where: { id, userId }
    });

    res.status(201).json(punchRecord);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

// 查看打卡历史记录
router.get('/:id/history', authenticateToken, async (req, res) => {
  const { id } = req.params;
  const { month } = req.query; // 从查询参数获取月份
  const userId = req.user.id; // 使用JWT中的userId

  try {
    // 首先验证打卡计划是否属于用户
    const punchPlan = await PunchPlan.findOne({ where: { id, userId } });
    if (!punchPlan) {
      return res.status(404).json({ message: 'Punch plan not found or not owned by user' });
    }

    // 构造查询条件
    const whereCondition = { punchPlanId: id };

    // 如果提供了月份参数，则添加日期范围条件
    if (month) {
      // 验证月份格式是否正确 (YYYYMM)
      if (!/^\d{6}$/.test(month)) {
        return res.status(400).json({ message: 'Invalid month format. Expected YYYYMM.' });
      }

      // 使用dayNo的前六位匹配年月
      whereCondition.dayNo = {
        [require('sequelize').Op.like]: `${month}%`
      };
    }

    // 查询打卡记录
    const punchRecords = await PunchRecord.findAll({
      where: whereCondition,
      order: [['dayNo', 'ASC'], ['created_at', 'ASC']]
    });

    res.json(punchRecords);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal Server Error' });
  }
});

module.exports = router;
